"""
四川麻将牌的定义和表示
"""
from enum import Enum
from typing import List, Tuple


class Suit(Enum):
    """麻将牌的花色"""
    BAMBOO = "筒"
    CHARACTER = "条"
    DOT = "万"


class Tile:
    """麻将牌的基类"""
    def __init__(self, suit: Suit, value: int, display: str):
        self.suit = suit
        self.value = value
        self.display = display
    
    def __str__(self):
        return self.display
    
    def __repr__(self):
        return self.display
    
    def __eq__(self, other):
        if not isinstance(other, Tile):
            return False
        return self.suit == other.suit and self.value == other.value
    
    def __hash__(self):
        return hash((self.suit, self.value))


class SuitTile(Tile):
    """序数牌（筒、条、万）"""
    def __init__(self, suit: Suit, value: int):
        display = f"{value}{suit.value}"
        super().__init__(suit, value, display)





class TileSet:
    """牌的集合"""
    def __init__(self, tiles: List[Tile] = None):
        self.tiles = tiles or []
    
    def add(self, tile: Tile):
        self.tiles.append(tile)
    
    def add_multiple(self, tiles: List[Tile]):
        self.tiles.extend(tiles)
    
    def remove(self, tile: Tile):
        if tile in self.tiles:
            self.tiles.remove(tile)
            return True
        return False
    
    def count(self, tile: Tile) -> int:
        return self.tiles.count(tile)
    
    def get_sorted_tiles(self) -> List[Tile]:
        """按花色和数值排序"""
        def sort_key(tile):
            suit_order = {Suit.BAMBOO: 0, Suit.CHARACTER: 1, Suit.DOT: 2}
            return (suit_order[tile.suit], tile.value)
        
        return sorted(self.tiles, key=sort_key)
    
    def to_string(self) -> str:
        return "".join(str(tile) for tile in self.get_sorted_tiles())
    
    def __len__(self):
        return len(self.tiles)
    
    def __iter__(self):
        return iter(self.tiles)


def create_standard_mahjong_set() -> List[Tile]:
    """创建一副标准的四川麻将牌（只有序数牌，没有字牌）"""
    tiles = []
    
    # 添加序数牌（筒、条、万，每个1-9各4张）
    for suit in [Suit.BAMBOO, Suit.CHARACTER, Suit.DOT]:
        for value in range(1, 10):
            for _ in range(4):
                tiles.append(SuitTile(suit, value))
    
    return tiles


def parse_tile_string(tile_str: str) -> List[Tile]:
    """从字符串解析麻将牌列表"""
    tiles = []
    i = 0
    while i < len(tile_str):
        # 处理序数牌（两个字符）
        if i + 1 < len(tile_str):
            value_str = tile_str[i]
            suit_char = tile_str[i + 1]
            
            if value_str.isdigit() and suit_char in [s.value for s in [Suit.BAMBOO, Suit.CHARACTER, Suit.DOT]]:
                value = int(value_str)
                for suit in [Suit.BAMBOO, Suit.CHARACTER, Suit.DOT]:
                    if suit.value == suit_char:
                        tiles.append(SuitTile(suit, value))
                        break
                i += 2
            else:
                i += 1
        else:
            i += 1
    
    return tiles